import { Stud } from "../Stud"
import { Usage } from "../StudUsage"
import { Cable } from "./Cable"

export class SPI extends Cable {
    constructor(title: string, public name: string, sck?: Stud, mosi?: Stud, miso?: Stud) {
        super("spi", title, name, -1)
        this.mapDefaultHostStuds[Usage.spisck] = sck
        this.mapDefaultHostStuds[Usage.spimosi] = mosi
        this.mapDefaultHostStuds[Usage.spimiso] = miso
    }

    isValid(): boolean {
        return this.mapHostStuds[Usage.spisck]!=undefined 
            && ( this.mapHostStuds[Usage.spimosi]!=undefined || this.mapHostStuds[Usage.spimiso]!=undefined )
    }

    public generateSetupCode(indent=0, freeFirst=false){
        if(!this.mapHostStuds[Usage.spisck]) {
            return ""
        }
        let sckpin = this.mapHostStuds[Usage.spisck]?.info.pin
        let mosipin = this.mapHostStuds[Usage.spimosi]?
            this.mapHostStuds[Usage.spimosi]?.info.pin: "-1"
        let misopin = this.mapHostStuds[Usage.spimiso]?
            this.mapHostStuds[Usage.spimiso]?.info.pin: "-1"

        return `${"\t".repeat(indent)}beapi.spi.setup(${this.name},${sckpin},${mosipin},${misopin})\n`
    }

    public isIoMux() {
        if(this.mapHostStuds[Usage.spimosi] && this.mapHostStuds[Usage.spimosi]?.info.pin!=13){
            return false
        }
        if(this.mapHostStuds[Usage.spimiso] && this.mapHostStuds[Usage.spimiso]?.info.pin!=12){
            return false
        }
        if(this.mapHostStuds[Usage.spisck] && this.mapHostStuds[Usage.spisck]?.info.pin!=14){
            return false
        }
        return true
    }

}